#include "timer.h"

#define TMR_UNIT            (M4_TMR02)
#define ENABLE_TMR0      (PWC_Fcg2PeriphClockCmd(PWC_FCG2_PERIPH_TIM02, Enable))

#define CMP_VALUE (65536)

void timerInit(void)
{
    stc_tim0_base_init_t stcTimerCfg;

    MEM_ZERO_STRUCT(stcTimerCfg);

    /* Enable XTAL32 */
    CLK_Xtal32Cmd(Enable);

    /* Timer0 peripheral enable */
    ENABLE_TMR0;
    /*config register for channel A */
    stcTimerCfg.Tim0_CounterMode = Tim0_Async;
    stcTimerCfg.Tim0_AsyncClockSource = Tim0_LRC;
    stcTimerCfg.Tim0_ClockDivision = Tim0_ClkDiv4;
    stcTimerCfg.Tim0_CmpValue = (uint16_t)(CMP_VALUE - 1u);
    TIMER0_BaseInit(TMR_UNIT,Tim0_ChannelA,&stcTimerCfg);

    /*start timer0*/
    TIMER0_Cmd(TMR_UNIT,Tim0_ChannelA,Enable);
}

// 可计数149小时,暂时不考虑溢出
static uint32_t time;
// 计数一次约等于0.125ms
// 7.5s溢出一次，足够处理了
void timerUpdate(void)
{
    static uint16_t prevCnt;
    uint16_t t = (uint16_t)((TMR_UNIT->CNTAR)&0xFFFFu);		
    uint8_t delta = 0;
    if (t < prevCnt)							
    {												
        delta = (CMP_VALUE - prevCnt + t);			
    }												
    else
    {
        delta = (t - prevCnt);
    }
    // 该芯片定时器有bug
    // 有时会出现计数倒退1的数值，导致delta溢出
    // 所以要做一下处理
    if (delta == 0xFF)
    {
        delta = 1;
    }
    time += delta;
    prevCnt = t;
}

uint32_t getTime(void)
{
    return time;
}

// 每次计数的时间，单位秒(根据实际来调整)
const float coff = 0.000125f;
// 传入上一次的时间，会自动更新时间
float getDt(uint32_t *prevT) 
{
	float result = coff * (time - *prevT);
    if (result > 0.1f)
    {
        result = 0.002f;
    }

	*prevT = time;
	return result;
}
